package cn.yunhe.servlet;

import cn.yunhe.entity.Page;
import cn.yunhe.entity.Product;
import cn.yunhe.service.ProductService;
import cn.yunhe.util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/GetProductServlet")
public class GetProductServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String keyword =request.getParameter("keyword");
        if(keyword==null ||keyword.trim().equals("")){
            keyword = null;
        }

        String epcname = request.getParameter("epcname");
        if(epcname==null ||epcname.trim().equals("")){
            epcname = null;
        }
        ProductService productService=new ProductService();
        String currPage = request.getParameter("pageIndex");
        if (currPage == null) {
            currPage = "1";
        }
        int pageIndex=Integer.parseInt(currPage);
        int totalDatas=productService.getProCount();
        int totalPages=PageUtil.getTotalPages(totalDatas);
        if (pageIndex < 1) {
            pageIndex = 1;
        }
        if (pageIndex > totalPages) {
            pageIndex = totalPages;
        }

        /*List<Product> productList=productService.getAllproBypage(pageIndex);*/
        Page page = new Page();
        page.setPageStart(pageIndex);
        page.setPageSize(PageUtil.PAGE_SIZE);
        page.setKeyword(keyword);
        page.setEpcname(epcname);
        List<Product> productList=productService.getAllproBypage2(page);
        request.setAttribute("epcname",epcname);
        request.setAttribute("keyword",keyword);
        request.setAttribute("pageIndex",pageIndex);
        request.setAttribute("productList",productList);
        request.setAttribute("totalPages",totalPages);
        request.getRequestDispatcher("product-list.jsp").forward(request,response);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
